<?php
error_reporting(E_ALL ^E_NOTICE);
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

$_MAMBOTS->registerFunction( 'onPayProsessStart', 'jeProcessPayPalStart' );
$_MAMBOTS->registerFunction( 'onPayProsessFinish', 'jeProcessPayPalFinish' );
function jcsPPGetInfo()
{

$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('www.paypal.com', 80, $errno, $errstr, 30);
if (!$fp) {

} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0) {

return $_POST;
}
else if (strcmp ($res, "INVALID") == 0) {
error_log("The response from IPN was: $res\n",3, '/home/virtual/she-makes-the-rules.com/webroot/htdocs/mambots/system/log.txt');
}
}
fclose ($fp);
}

return false;
}

function jeProcessPayPalFinish()
{
Global $my, $database, $mosConfig_live_site;

$processor = mosGetParam( $_REQUEST, 'processor');
if($processor != '.paypal') return false;

$query = "SELECT id"
. "\n FROM #__mambots"
. "\n WHERE element = 'joomlaequipment.payprocessor{$params[processor]}'"
. "\n AND folder = 'system'"
;
$database->setQuery( $query );
$id = $database->loadResult();
$mambot = new mosMambot( $database );
$mambot->load( $id );
$botParams = new mosParameters( $mambot->params );

if( mosGetParam( $_REQUEST, 'pay') == 'ipn' || $botParams->get('ipn'))
{
$s_info = jcsPPGetInfo();
//$s_id = jcsGetSubscrId($s_info['']);
//$s_info = $_GET;
$order['id'] = mosGetParam( $_REQUEST, 'order_id');
switch($s_info['txn_type'])
{

case "web_accept":
case "subscr_payment":
$order['user'] = $s_info['custom'] ? $s_info['custom'] : $my->id;
if(key_exists('subscr_id', $s_info))
{
$order['gateway_id'] = $s_info['subscr_id'].' '.$s_info['txn_id'];
}
else
{
$order['gateway_id'] = $s_info['txn_id'];
}
$order['price'] = $s_info['payment_gross'];
if($s_info['payment_status'] == 'Completed')
$order['pay'] = 'success';
else
$order['pay'] = 'fail';
break;

case "subscr_failed":
$order['user'] = $s_info['custom'] ? $s_info['custom'] : $my->id;
$order['gateway_id'] = $s_info['subscr_id'];
$order['price'] = $s_info['payment_gross'];
$order['pay'] = 'fail';
break;


case "subscr_eot":
case "subscr_cancel":
$sql = "UPDATE #__jcs_user_subscr SET published = 0 WHERE gateway_id LIKE '{$s_info[subscr_id]}%'";
$database->setQuery($sql);
$database->query();
break;
}
}
else
{
$order['id'] = mosGetParam( $_REQUEST, 'order_id');
$order['pay'] = mosGetParam( $_REQUEST, 'pay');
$order['gateway'] = $processor;
$order['gateway_id'] = mosGetParam( $_REQUEST, 'txn_id', date("m-d")."-".$order['id']);
$order['price'] = mosGetParam( $_REQUEST, 'amount');
}

//session_start();
//if((float)$_SESSION['price'] != (float)$order['price'])
//{
//$order['pay'] = 'fail';
//}

return $order;
}

function jeProcessPayPalStart( $params )
{
Global $my, $database, $mosConfig_live_site, $mosConfig_absolute_path,
$JCS_ORDER_COMPLETE, $JCS_ORDER_INCOMPLETE;

if($params['processor'] != '.paypal') return;

if (file_exists( $mosConfig_absolute_path.'/components/com_jcs/languages/'.$mosConfig_lang.'.php' ))
include_once( $mosConfig_absolute_path.'/components/com_jcs/languages/'.$mosConfig_lang.'.php' );
else
require_once( $mosConfig_absolute_path.'/components/com_jcs/languages/english.php' );

$query = "SELECT id"
. "\n FROM #__mambots"
. "\n WHERE element = 'joomlaequipment.payprocessor{$params[processor]}'"
. "\n AND folder = 'system'"
;
$database->setQuery( $query );
$id = $database->loadResult();
$mambot = new mosMambot( $database );
$mambot->load( $id );
$botParams = new mosParameters( $mambot->params );
session_start();
$_SESSION['price'] = $params['order_id'];

$param['option'] = mosGetParam( $_REQUEST, 'option');
$param['task'] = 'pay';
$param['processor'] = $params['processor'];
$param['order_id'] = $params['order_id'];
$param['amount'] = floatval($params['order_amount']);
$return = urlencode($mosConfig_live_site.'/index.php?'.jpArray2Url($param).'&pay=success');
$cancel_return = urlencode($mosConfig_live_site.'/index.php?'.jpArray2Url($param).'&pay=fail');

IF($botParams->get('ipn'))
{
$return = urlencode($mosConfig_live_site.'/index.php?option=com_jcs&smsg='.$JCS_ORDER_COMPLETE);
$cancel_return = urlencode($mosConfig_live_site.'/index.php?option=com_jcs&smsg='.$JCS_ORDER_INCOMPLETE);
$notify = urlencode($mosConfig_live_site.'/index.php?'.jpArray2Url($param).'&pay=ipn');
}

unset($param);

$param['notify_url'] = $notify;
$param['return'] = $return;
$param['cancel_return'] = $cancel_return;
$param['amount'] = $params['order_amount'];
$param['cmd'] = "_xclick";
$param['custom'] = $my->id;
$param['rm'] = "2";
$param['business'] = urlencode($botParams->def( 'email'));
$param['currency_code'] = $botParams->def( 'currency');
$param['item_name'] = strval($params['order_title']);

if($botParams->def('requre'))
{
$sql = "SELECT * FROM #__jcs_plans WHERE id = '{$params[order_id]}'";
$database->setQuery( $sql );
$rows = $database->loadObjectList();
$row = $rows[0];

unset($param['amount']);

$param['cmd'] = "_xclick-subscriptions";
$param['a3'] = $params['order_amount'];
$param['t3'] = strtoupper(substr($row->days_type,0,1));
$param['p3'] = $row->days;
$param['src'] = "1";
$param['sra'] = "1";
$param['no_shipping'] = "2";
$param['no_note'] = "1";
}
if($botParams->def('tax'))
{
$param['tax'] = $botParams->def('tax');
}

if(!$param['business'] || !$param['currency_code'] || !$param['item_name'] || !$params['order_amount'])
{
echo "<P><h1>Error Payment Processing: some of the params passed are empty</h1></P>";
return;
}
//$url = 'https://www.sandbox.paypal.com/cgi-bin/webscr?'.jpArray2Url($param);
$url = 'https://www.paypal.com/us/cgi-bin/webscr?'.jpArray2Url($param);
//$url = 'https://www.paypal.com/subscriptions/'.jpArray2Url($param);
//echo str_replace("&", "<BR>", urldecode($url));
header("location: $url");
}

if(!defined('JP_IMPLODE'))
{
define('JP_IMPLODE', 1);
function jpArray2Url($param)
{
foreach($param AS $k => $v)
{
$out[] = "$k=$v";
}
return implode('&', $out );
}
}
?>